import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.spi.http.HttpContext;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/ValidateCodeServlet")
public class ValidateCodeServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建一张图片
        int width=300;//验证码宽度
        int height=90;//验证码高度
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        //绘制图片
        //从图片对象中获取绘制图片的“笔”
        Graphics pen=image.createGraphics();
        //绘制背景
        pen.setColor(getRandomColor());
        //fillRect:绘制实心矩形
        pen.fillRect(0,0,width,height);
        //绘制验证码字符串
        int letterNum=4;//验证码图片上的字符的个数
        int space=20;//验证码图片上两个字母之间的空隙
        int letterWidth=(width-(letterNum+1)*space)/letterNum;//计算每个字母占据的宽度
        //for循环每循环一次,绘制一个字母(小写字母的ASCII码97-122)
        String vCode="";
        Random random=new Random();
        for(int i=0;i<letterNum;i++){
            //随机生成一个小写字母
            int ascii=random.nextInt(26)+97;//97--122
            byte[] bs={(byte) ascii};
            String letter=new String(bs);
            vCode=vCode+letter;
            //drawString:绘制字母
            pen.setColor(getRandomColor());
            pen.setFont(new Font("Gulim", Font.BOLD,70));
            pen.drawString(letter,space+(letterWidth+space)*i,height-space);
        }
        //将生成的验证码存入到session
        HttpSession session=req.getSession();
        session.setAttribute("vCode",vCode);

        //图片绘制完成后,将图片通过response的输出流响应到客户端
        ImageIO.write(image,"png",resp.getOutputStream());
    }
    //产生一种随机颜色
    public Color getRandomColor(){
        Random random=new Random();
        int r= random.nextInt(256);
        int g=random.nextInt(256);
        int b=random.nextInt(256);
        Color color=new Color(r,g,b);
        return color;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}